from django.core.management.base import BaseCommand
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from catalog.models import Book, Author, BookInstance

class Command(BaseCommand):
    help = '创建用户组和权限'

    def handle(self, *args, **options):
        # 创建图书管理员组
        librarian_group, created = Group.objects.get_or_create(name='Librarian')
        if created:
            self.stdout.write('成功创建图书管理员组')

        # 创建普通用户组
        member_group, created = Group.objects.get_or_create(name='Member')
        if created:
            self.stdout.write('成功创建普通用户组')

        # 获取所有相关模型的权限
        book_permissions = Permission.objects.filter(
            content_type__model__in=['book', 'bookinstance', 'author']
        )

        # 为图书管理员组分配所有权限
        for perm in book_permissions:
            librarian_group.permissions.add(perm)
        self.stdout.write('已为图书管理员组分配所有权限')

        # 为普通用户组分配查看权限
        view_permissions = Permission.objects.filter(
            codename__in=['view_book', 'view_author', 'view_bookinstance']
        )
        for perm in view_permissions:
            member_group.permissions.add(perm)
        self.stdout.write('已为普通用户组分配查看权限')

        self.stdout.write(self.style.SUCCESS('权限设置完成！')) 